<template>
  <el-card class="box-card card-item mb-5 border-1" shadow="never" :body-style="{ padding: '20px' }">
    <div class="flex items-center">
      <el-text class="mr-2">分类名称</el-text>
      <el-input v-model="searchCategoryName" placeholder="请输入（模糊查询）" style="width: 200px"/>

      <el-text class="mr-2">创建日期</el-text>
      <el-date-picker v-model="pickDate" type="daterange" range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间" :shortcuts="shortcuts" size="default" @change="datepickerChange"
                    style="width: 260px"/>

      <el-button type="primary" :icon="Search" @click="getTableData" class="ml-9">查询</el-button>
      <el-button :icon="RefreshRight" @click="reset" class="ml-3">重置</el-button>
    </div>
  </el-card>

  <el-card class="box-card card-item border-1" shadow="never">
    <!-- 第二个card内容 -->
    <!-- 新增按钮 -->
    <div class="flex justify-between">
      <div>
        <el-button type="primary" @click="showCategoryDialog()">
          <el-icon class="mr-1">
            <Plus/>
          </el-icon>
          新增
        </el-button>
        <el-button type="danger" @click="batchDeleteSubmit()" :disabled="!selectedRows.length">
          <el-icon class="mr-1">
            <Delete/>
          </el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <el-table :data="tableData" stripe style="width: 100%" class="mt-4" v-loading="tableLoading"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="categoryId" label="ID" width="200"/>
      <el-table-column prop="name" label="分类名称" width="180">

      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="showCategoryDialog(scope.row)" class="mr-2">
            <el-icon class="mr-1">
              <Edit/>
            </el-icon>
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="batchDeleteSubmit([scope.row])">
            <el-icon class="mr-1">
              <Delete/>
            </el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="mt-5 flex item-center justify-center">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <!-- 分类表单 -->
  <el-dialog v-model="isCategoryDialogShow" :title="form.categoryId ? '编辑分类' : '新增分类'" width="30%" :show-close="false" draggable>
    <el-form :model="form" ref="formRef" label-position="top" :size="large" :rules="rules">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name" autocomplete="off" size="large" maxlength="10" show-word-limit clearable/>
      </el-form-item>
    </el-form>
    <template #footer>
            <span class="dialog-footer">
                <el-button @click="hideCategoryDialog">取消</el-button>
                <el-button type="primary" @click="handleSubmit">
                    提交
                </el-button>
            </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, onMounted, watch} from 'vue'
import {addCategory, getCategoryPageList, deleteCategory, updateCategory} from '@/api/admin/category'
import {showMessage} from '@/composables/util'
import moment from 'moment';
import {Search, RefreshRight} from '@element-plus/icons-vue'

const isCategoryDialogShow = ref(false)

const searchCategoryName = ref('')
const pickDate = ref('')
const startDate = reactive({})
const endDate = reactive({})

const reset = () => {
  pickDate.value = ''
  startDate.value = null
  endDate.value = null
  searchCategoryName.value = ''
}

const datepickerChange = (e) => {
  startDate.value = moment(e[0]).format('YYYY-MM-DD HH:mm:ss')
  endDate.value = moment(e[1]).format('YYYY-MM-DD HH:mm:ss')
}

const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

const form = reactive({
  id: '',
  name: ''
})

const formRef = ref(null)
const rules = {
  name: [
    {required: true, message: '请输入分类名称', trigger: 'blur'},
    {min: 1, max: 10, message: '分类名称字数要求大于1个字符，小于20个字符', trigger: 'blur'},
  ]
}

const showCategoryDialog = (row) => {
  if(row) {
    form.categoryId = row.categoryId
    form.name = row.name
  }
  isCategoryDialogShow.value = true
}

const hideCategoryDialog = () => {
  form.id = ''
  form.name = ''
  isCategoryDialogShow.value = false
}

const handleSubmit = () => {
  const request = form.categoryId ? updateCategory(form) : addCategory(form)
  request.then((e) => {
    if (e.success == false) {
      showMessage(e.message, 'warning', 'message')
      return
    }

    showMessage(form.id ? '修改成功' : '添加成功', 'success', 'message')
    hideCategoryDialog()
    getTableData()
  })
}

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const tableLoading = ref(false)

// 获取分类列表数据
const getCategoryList = async () => {
  console.trace('getCategoryList called') // 用于调试
  tableLoading.value = true
  try {
    const res = await getCategoryPageList({
      current: currentPage.value,
      size: pageSize.value,
      name: searchCategoryName.value
    })
    tableData.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error(error)
  } finally {
    tableLoading.value = false
  }
}

// 只在 mounted 时调用一次
onMounted(() => {
  getCategoryList()
})

// 分页处理方法
const handleSizeChange = (val) => {
  pageSize.value = val
  getCategoryList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getCategoryList()
}

// 搜索处理方法
const handleSearch = () => {
  currentPage.value = 1 // 重置页码
  getCategoryList()
}

// 重置方法
const handleReset = () => {
  searchCategoryName.value = ''
  currentPage.value = 1
  getCategoryList()
}

// 添加选择行相关的变量和方法
const selectedRows = ref([])

const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 批量删除提交
const batchDeleteSubmit = (rows) => {
  const deleteRows = rows || selectedRows.value
  if (deleteRows.length === 0) {
    showMessage('请选择要删除的分类', 'warning')
    return
  }

  ElMessageBox.confirm(
      `是否确认要删除选中的 ${deleteRows.length} 个分类?`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        const ids = deleteRows.map(row => row.categoryId)
        // 修改为传递对象
        deleteCategory({data: ids}).then((e) => {
          if (e.success == true) {
            showMessage('删除成功', 'success')
            getTableData()
          } else {
            showMessage(e.message, 'warning')
          }
        })
      })
}

</script>

<style scoped>
.card-item + .card-item {
  margin-top: 16px;
}

.el-pagination {
  margin-top: 20px;
}

/* 添加以下样式来解决间距和对齐问题 */
.flex.items-center {
  display: flex !important;
  align-items: center !important;
  min-height: 40px !important;
}

/* 日期选择器样式 */
:deep(.el-date-editor.el-input__wrapper) {
  margin-right: 36px !important;
  display: flex !important;
  align-items: center !important;
  height: 32px !important;
  width: 240px !important;
}

.el-input {
  margin-right: 24px !important;
}

.el-text {
  margin-right: 12px !important;
}

/* 确保按钮有足够的左边距 */
.el-button.ml-9 {
  margin-left: 36px !important;
}

/* 如果上面的选择器不够具体，可以尝试这个 */
.box-card :deep(.el-date-editor.el-input__wrapper),
.box-card :deep(.el-date-picker) {
  width: 240px !important;
  max-width: 240px !important;
}
</style>